package com.xujl.datalibrary;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.changan.remote.assistant.RemoteDelegate;
import com.xujl.datalibrary.bean.RequestBean;
import com.xujl.datalibrary.task.TaskCallback;
import com.xujl.datalibrary.task.TaskFactory;
import com.xujl.datalibrary.task.TaskInterface;
import com.xujl.datalibrary.util.JsonParseUtils;

/**
 * <pre>
 *     @author : xujl
 *     e-mail : 597355068@qq.com
 *     time   : 2018/11/14
 *     desc   : 远程服务器
 *     version: 1.0
 * </pre>
 */
public class RemoteServer extends Service implements RemoteDelegate.ReceiveEventListener {
    private RemoteDelegate mRemoteDelegate;

    @Override
    public void onCreate () {
        super.onCreate();
        mRemoteDelegate = new RemoteDelegate(this);
    }

    @Nullable
    @Override
    public IBinder onBind (Intent intent) {
        return mRemoteDelegate.getIBinder();
    }

    @Override
    public void onReceiveEvent (String json) {
        final RequestBean taskBean = JsonParseUtils.fromJson(json, RequestBean.class);
        //创建任务处理者
        final TaskInterface taskWorker = TaskFactory.createTaskWorker(taskBean);
        //执行任务
        taskWorker.runTask(taskBean, new TaskCallback() {
            @Override
            public void onTaskComplete (String json) {
                //任务完成，返回客户端结果
                mRemoteDelegate.dispatchEvent(taskBean.getRequestCode(), json);
            }
        });
    }

    @Override
    public int onStartCommand (Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


}
